package com.longrise.android.byjk.plugins.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.CloseModeConstants;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.ActivityUtil;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.InputBoxView;

/**
 * Created by callxkj on 2016/12/15.
 * 修改密码
 */

public class ChangePasswordActivity extends BaseActivity implements View.OnClickListener, TextWatcher {

    private static final String TAG = "ChangePasswordActivity";

    private InputBoxView mInput_Pass;

    private InputBoxView mInput_Pass_;

    private InputBoxView mInput_Pass_Agin;

    private Button mBtn_Update;

    private ImageView mIvVfcode; //验证码

    private EditText mEtvfcode;

    private String usersfzh;
    private TextView mTvyhzh;
    private Toolbar mToolbar;
    private ImageView mVfcode;

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.lfview_updatepassword;
    }

    @Override
    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle("修改密码");
        setSupportActionBar(mToolbar);

        mTvyhzh = (TextView) findViewById(R.id.changePw_yhzh);
        mInput_Pass = (InputBoxView) findViewById(R.id.edit_pass);
        mInput_Pass_ = (InputBoxView) findViewById(R.id.imput_pass_);
        mInput_Pass_Agin = (InputBoxView) findViewById(R.id.imput_pass_agin);
        mBtn_Update = (Button) findViewById(R.id.button_updatepass);
        mBtn_Update.setEnabled(false);
        mIvVfcode = (ImageView) findViewById(R.id.vfcode_pic2);
        mIvVfcode.setScaleType(ImageView.ScaleType.FIT_XY);
        mEtvfcode = (EditText) findViewById(R.id.vfcode_text); //图片验证码输入框
        mVfcode = (ImageView) findViewById(R.id.vfcode_pic1);
        initData();
        initEvent();

        Tracker_Google.getInstance().addGoogleScreenName("修改密码");
    }

    private void initData() {
        usersfzh = UserInfor.getInstance().getUserName();
        if (usersfzh != null) {
            mTvyhzh.setText(usersfzh);
        }
        loadVfcode();
    }

    private void initEvent() {
        mBtn_Update.setOnClickListener(this);
        mInput_Pass_.setRightClickMode(InputBoxView.PASSWORD);
        mInput_Pass_.setTextMode(InputBoxView.PASSWORD);
        mInput_Pass_Agin.setRightClickMode(InputBoxView.PASSWORD);
        mInput_Pass_Agin.setTextMode(InputBoxView.PASSWORD);
        mInput_Pass.setRightClickMode(InputBoxView.PASSWORD);
        mInput_Pass.setTextMode(InputBoxView.PASSWORD);
        mIvVfcode.setOnClickListener(this);
        mEtvfcode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String CheckCode = mEtvfcode.getText().toString().trim();
                if (!TextUtils.isEmpty(CheckCode) && !"".equals(CheckCode)) {
                    mVfcode.setSelected(true);
                } else {
                    mVfcode.setSelected(false);
                }

            }
        });

        //判断是否有输入框没有填写
        mEtvfcode.addTextChangedListener(this);//图片验证码
        mInput_Pass.getEditText().addTextChangedListener(this);// 原密码
        mInput_Pass_.getEditText().addTextChangedListener(this); //新密码
        mInput_Pass_Agin.getEditText().addTextChangedListener(this); //确认密码

        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void loadVfcode() {
        RoundCornersTransformation transformation =
                new RoundCornersTransformation(mContext,
                        AppUtil.dip2px(4),
                        RoundCornersTransformation.CornerType.RIGHT);
        GlideUrl glideUrl = new GlideUrl(UrlConstants.VFCODE_URL,
                new LazyHeaders
                        .Builder()
                        .addHeader("Cookie", LoadDataManager.getInstance().getCookie())
                        .build());
        Glide.with(this)
                .load(glideUrl)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .bitmapTransform(transformation)
                .into(mIvVfcode);
    }

    /**
     * 确认提交
     */
    private void toConfirm() {
        String tpvfcode = mEtvfcode.getText().toString().trim(); //图片验证码
        String oldPW = mInput_Pass.getText(); // 原密码
        String password = mInput_Pass_.getText();  //新密码
        String password2 = mInput_Pass_Agin.getText(); //确认密码

        EntityBean bean = new EntityBean();
        bean.set("username", usersfzh);
        bean.set("oldpwd", oldPW);
        bean.set("newpwd", password);
        bean.set("imgcode", tpvfcode);
        bean.set("confirmpwd", password2);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        mBtn_Update.setClickable(false);
        DZZWTools.showWaitDialog(this);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_login_uChangePWD2", fbean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean bean = (EntityBean) result;
                    String resultdesc = (String) bean.get("resultdesc");
                    int resultstate = (Integer) bean.get("resultstate");
                    if (resultstate == 1) {
                        LoadDataManager.getInstance().setReloginBean(null);
                        CloseModeConstants.setWillToLogin(true);
                        ActivityUtil.removeActivity(ChangePasswordActivity.this);
                        ActivityUtil.finishAllAcivity();
                        Intent intent = new Intent(ChangePasswordActivity.this, LoginActivity.class);
                        startActivity(intent);

//                        new BbJpushHelper().stopAliasNotification(mContext);


                        finish();
                    } else {
                        Tracker_Google.getInstance().addEvent("Change-password", "Failed-changepw", "修改密码失败");
                    }
                    DZZWTools.showToast(ChangePasswordActivity.this, resultdesc, 0);
                    Tracker_Google.getInstance().addEvent("Change-password", "Success-changepw", "修改密码成功");
                } catch (Exception e) {
                    Tracker_Google.getInstance().addEvent("Change-password", "Failed-changepw", "修改密码失败");
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(ChangePasswordActivity.this, getResources().getString(R.string.networkerror), 0);
            }

            @Override
            public void onFinished(String key, String service) {
                mBtn_Update.setClickable(true);
                DZZWTools.dismissDialog(null);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_updatepass:
                toConfirm();
                break;
            case R.id.vfcode_pic2: //图片验证码
                loadVfcode();
                break;
        }
    }


    //-------以下三个为输入框字数的更改--------
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        boolean b = checkText();
        if (b) {
            mBtn_Update.setEnabled(true);
        } else {
            mBtn_Update.setEnabled(false);
        }
    }
    //-------以上三个为输入框字数的更改--------

    /**
     * 检查是否全部text有填写
     *
     * @return 全部填写返回true
     */
    private boolean checkText() {
        String tpvfcode = mEtvfcode.getText().toString().trim(); //图片验证码
        if (TextUtils.isEmpty(tpvfcode)) {
            // DZZWTools.showToast(ChangePasswordActivity.this, getString(R.string.tpvfcode_null), 0);
            return false;
        }

        String oldPW = mInput_Pass.getText(); // 原密码
        if (TextUtils.isEmpty(oldPW)) {
            //DZZWTools.showToast(ChangePasswordActivity.this, getString(R.string.input_oldpw), 0);
            return false;
        }

        String password = mInput_Pass_.getText();  //新密码
        if (TextUtils.isEmpty(password)) {
            //DZZWTools.showToast(ChangePasswordActivity.this, getString(R.string.input_newpw), 0);
            return false;
        }

        String password2 = mInput_Pass_Agin.getText(); //确认密码
        if (TextUtils.isEmpty(password2)) {
            // DZZWTools.showToast(ChangePasswordActivity.this, getString(R.string.input_confirm), 0);
            return false;
        }
        return true;
    }
}
